<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/10
 * Time: 11:43
 */


namespace wechat\action;

use EasyWeChat\Kernel\Messages\Location;
use Symfony\Component\HttpFoundation\Request;
use wechat\util\WechatPlatform;

class  api_open
{

    /**
     * 开放平台生成授权的URL
     */
    public function getPreAuthorizationUrl()
    {
        $url = WechatPlatform::getOpenPlatformInstance()->getPreAuthorizationUrl(CALL_BACK_URL_OPEN); // 传入回调URI即可
        echo "<a href='{$url}'>微信授权</a>";
    }

    /**
     * 静默授权
     */
    public function getUserInfo()
    {
        WechatPlatform::getOfficiaInstance()->oauth->scopes(['snsapi_base'])->redirect()->send();
    }

    /**
     * 公众号发送模板消息
     */
    public function sendTemplate()
    {
        WechatPlatform::getOfficiaInstance()->template_message->send([
            'touser' => $_SESSION['open_id'],
            'template_id' => 'c-61sqR2jUjDz5l_9Jl_iZGUztNf-L0C5nJQsnWiAmg',
            'url' => 'https://easywechat.org',
            'data' => [
                'first' => '恭喜您中奖！',
                'keyword1' => 'LEE SMILE 会员积分幸运抽奖',
                'keyword2' => '获得100分幸运积分',
                'keyword3' => '2017年6月22日',
                'keyword4' => 'Robbin Qian',
                'remark' => '感谢您参与活动！'
            ],
        ]);
    }

    /**
     * H5返回JSSDK签名
     */
    public function getJssdk()
    {
        //$this->getCache()->has($cacheKey)
        //print_r(WechatPlatform::getOfficiaInstance()->jssdk->getCache());
        $url = $_REQUEST['url'];
        WechatPlatform::getOfficiaInstance()->jssdk->setUrl($url);
        $wx_config = WechatPlatform::getOfficiaInstance()->jssdk->buildConfig(array('checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'showOptionMenu',
            'getLocation',
            'getNetworkType'), false, false, true);
        header("Access-Control-Allow-Origin:*");
        echo $wx_config;
        die;
    }

    /**
     * 获取草稿列表
     */
    public function getDrafts()
    {
        list($auth_app_id, $authorizer_refresh_token) = $this->getAuthApp();
        $miniProgram = WechatPlatform::getOpenPlatformInstance()->miniProgram($auth_app_id, $authorizer_refresh_token);
        $draft_list=$miniProgram['code_template']->getDrafts();
        header("Access-Control-Allow-Origin:*");
        echo $draft_list;
        exit();
    }

    /**
     * 接口A: 适用于需要的码数量较少的业务场景
     * @param string $file_path
     */
    public function getLimitCode($file_path = "upload")
    {
        list($auth_app_id, $authorizer_refresh_token) = $this->getAuthApp();
        $miniProgram = WechatPlatform::getOpenPlatformInstance()->miniProgram($auth_app_id, $authorizer_refresh_token);
        // 或者指定颜色
        $response = $miniProgram->app_code->get(BASE_PATH . $file_path, [
            'width' => 600,
            'line_color' => [
                'r' => 105,
                'g' => 166,
                'b' => 134,
            ],
        ]);
        // $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例，失败时为数组或者你指定的 API 返回格式
        // 保存小程序码到文件
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(BASE_PATH . "/" . $file_path, "{$auth_app_id}.png");
        }
        header("Location: " . MAIN_HOST . "/" . $file_path . "/" . "{$auth_app_id}.png");
    }

    /**
     * 接口B：适用于需要的码数量极多，或仅临时使用的业务场景
     * @param string $file_path
     */
    public function getUnlimitCode($file_path = "upload")
    {
        list($auth_app_id, $authorizer_refresh_token) = $this->getAuthApp();
        $miniProgram = WechatPlatform::getOpenPlatformInstance()->miniProgram($auth_app_id, $authorizer_refresh_token);
        $response = $miniProgram->app_code->getUnlimit('scene-value', []);
        $filename = "can not be save";
        // 保存小程序码到文件
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(BASE_PATH . $file_path);
        }
        header("Location: " . MAIN_HOST . "/" . $file_path . "/" . $filename);
    }

    /**
     * 获取小程序二维码
     * @param string $file_path
     */
    public function getMiniQRCode($file_path = "upload")
    {
        list($auth_app_id, $authorizer_refresh_token) = $this->getAuthApp();
        $miniProgram = WechatPlatform::getOpenPlatformInstance()->miniProgram($auth_app_id, $authorizer_refresh_token);
        $response = $miniProgram->app_code->getQrCode(BASE_PATH . $file_path);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(BASE_PATH . $file_path, "{$auth_app_id}_1.png");
        }
        header("Location: " . MAIN_HOST . "/" . $file_path . "/" . "{$auth_app_id}_1.png");
    }

    public function getAuthApp()
    {
        $auth_account = WechatPlatform::getOpenPlatformInstance()['cache']->get("account_info");
        $auth_app_id = $auth_account["authorization_info"]["authorizer_appid"];
        $authorizer_refresh_token = $auth_account["authorization_info"]["authorizer_refresh_token"];
        return [$auth_app_id, $authorizer_refresh_token];
    }

    public function test()
    {
        // 创建 redis 实例
        $redis = new \Redis();
        $redis->connect(REDIS_HOST, 6379);
        echo $redis->get("component_verify_ticket");
    }


}